package com.rexolar.openapi.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rexolar.openapi.context.OpenContextUtil;
import com.rexolar.openapi.enums.ErrorCodeEnum;
import com.rexolar.openapi.exception.IllegalRequestException;
import com.rexolar.openapi.job.AppSyncJob;
import com.rexolar.openapi.service.impl.PartnerAppService;
import com.rexolar.openapi.utlis.EncryptUtil;
import com.rexolar.openapi.utlis.MacAddressUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description 用户认证拦截器
 * @Author  zhusiyu
 * @Date 2024/09/18
 * @Version 1.0
 */
@Component
@Slf4j
public class SignInterceptor implements HandlerInterceptor {

    @Autowired
    AppSyncJob appSyncJob;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true; // 不拦截 OPTIONS 请求
        }
        Map<String, String> paramsMap = OpenContextUtil.getContext().getParamsMap();
        checkHmac(paramsMap);
        return true;
    }

    private void checkHmac(Map<String, String> map) {
        Set<Map.Entry<String, String>> set = map.entrySet();
        Iterator<Map.Entry<String, String>> it = set.iterator();
        String sign = "";
        String appKey = "";
        Map<String, String> pras = new HashMap<>();

        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            String key = entry.getKey().trim();
            String value = entry.getValue();
            if (!"sign".equals(key)) {
                if (value == null) {
                    value = "";
                }
                pras.put(key, value.trim());
            }
            if ("sign".equals(key)) {
                sign = value;
            }
            if ("appKey".equals(key)) {
                appKey = value;
            }
        }
        if (StringUtils.isBlank(sign)) {
            throw new IllegalRequestException(ErrorCodeEnum.LESS_PARAMETERS_SIGN);
        }

        String appSecret = appSyncJob.getPartnerSecret(appKey);

        if (StringUtils.isBlank(appSecret)) {
            log.error("SignInterceptor$checkHmac error, appSecret is blank!appKey:{}, appSecret:{}", appKey, appSecret);
            throw new IllegalRequestException(ErrorCodeEnum.ILLEGAL_PARAMETERS_APPKEY_NOT_EXIST);
        }

        String signTmp = EncryptUtil.getToSign(pras, appSecret);
        if (!sign.equals(signTmp)) {
            log.error("SignInterceptor$checkHmac error!pras:{}, appSecret:{}, signTmp:{}",
                    pras, appSecret,signTmp);
            throw new IllegalRequestException(ErrorCodeEnum.ILLEGAL_PARAMETERS_SIGN_CHECK_ERROR);
        }
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }
    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
    }

    public static void main(String[] args) {
        String tokenStr = "dXl0MjlNeE44Y21BMFBtd2lpcHBWMEx6TGJoTk9WR0JHc1RFdGZQTXFyRkVkbEVqZnNONlIxNjNZTFlTYWJOOA==";
        String base64String = Base64.getEncoder().encodeToString(tokenStr.getBytes());
        System.out.println(base64String);
    }


}
